package com.xywy.find;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;
import com.xywy.R;
import com.xywy.common.BaseActivity;
import com.xywy.common.constants.ResultCode;
import com.xywy.common.util.Constants;
import com.xywy.common.util.ToastUtil;
import com.xywy.common.widget.MyProgress;
import com.xywy.common.widget.TitleBar2;
import com.xywy.find.bean.JkgcArticle;
import com.xywy.find.paser.JkgcArticlePaser;
import com.xywy.me.bean.UserKeeper;

/**
 * 健康广场每个条目进入后的页面
 * 
 * @author yangyu
 */
public class JkgcItemActivity extends BaseActivity implements OnClickListener {
	public static final String ID = "id";
	public static final String TARGET = "target";
	public static final String TITLE = "title";

	private TextView tvTitle; // 标题文字
	private TextView tvBack; // 返回按钮文字

	private TextView tv_curTitle;// 文章标题；
	private TextView tv_text;// 文章正文；
	private WebView webView;// 测试显示文章；

	private ImageView tv_jkgc_article_good;// 赞
	private ImageView tv_jkgc_article_share;// 分享
	private ImageView tv_jkgc_article_collect;// 收藏
	private Drawable collectDr;
	private Drawable shareDr;
	private Drawable goodD;

	private String title;// 文章标题
	private String id; // 当前文章id
	private String target;// 当前文章属于的类别
	private String titleStr;
	private String contentStr;

	private JkgcArticle article;// 当前内容实体类
	private JkgcArticlePaser paser;

	private String userId;
	private SharedPreferences spState;
	private Editor editor;
	private IWXAPI api;
	private int currentState;
	private int helpState;

	public static final String appid = "1001";
	public static final int Sta_Click = 2 ;//进入页面
	public static final int Sta_Collect = 0 ;//收藏
	public static final int Sta_Help = 1 ;//进入页面
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.find_jkzh_item_activity);
		api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
		this.preInit();
		this.initView();
		initTtile();
		getArticleData();
	}

	/**
	 * 从服务器获取数据
	 */
	private void getArticleData() {

		paser = new JkgcArticlePaser(JkgcItemActivity.this, handler,
				JkgcArticlePaser.ARTICLE);
		// 封装httpclient参数
		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("dir", target);
		params.put("art_id", id);
		String action = getString(R.string.find_jkgc_articles);
		paser.sendMsg(action, params, "get");
		beganProgressDialog();

	}

	/**
	 * 初始化头部标题
	 */
	private void initTtile() {

		// title
		TitleBar2 titleBar = (TitleBar2) findViewById(R.id.find_jkgc_title_bar);
		tvTitle = titleBar.getTitle();
		tvBack = titleBar.getTvBack();
		titleBar.getGo().setVisibility(View.INVISIBLE);
		titleBar.onClickBack(this);
		tvTitle.setText(title);
		tvBack.setText("返回");

	}

	/**
	 * 消息处理器
	 */
	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			stopProgressDialog();
			if (msg.arg1 == ResultCode.SUCCESS) {
				switch (msg.what) {
				case JkgcArticlePaser.ARTICLE:
					if (msg.obj == null) {
						Log.d(TAG, "解析json数据失败！");
						return;
					}
					article = (JkgcArticle) msg.obj;
					showDataOnView(article);
					getState();
					break;
				case JkgcArticlePaser.COLLECT:
					if (currentState == DEFAULT) {
						ToastUtil.showToast(JkgcItemActivity.this, "收藏成功", 1);
						currentState = COLLECTED;
						Stattistics(Sta_Collect);
					} else {
						ToastUtil.showToast(JkgcItemActivity.this, "取消收藏",1);
						currentState = DEFAULT;
					}
					setDrawable(currentState);
					break;
				case JkgcArticlePaser.FAILED:
					Toast.makeText(JkgcItemActivity.this, "访问网络失败", 1).show();
					break;
				case JkgcArticlePaser.FIND:
					String jsonStr = (String) msg.obj;
					currentState = DEFAULT;
					setDrawable(currentState);
					try {
						JSONObject jsonObject = new JSONObject(jsonStr);
						JSONArray jsonArray = jsonObject.getJSONArray("data");
						if (null != jsonArray && jsonArray.length() > 0) {
							for (int i = 0; i < jsonArray.length(); i++) {
								JSONObject json = jsonArray.getJSONObject(i);
								String tempId = json.optString("art_id");
								if (id.equals(tempId)) {
									currentState = COLLECTED;
									setDrawable(currentState);
									break;
								}
							}
						}
						tv_jkgc_article_collect.setEnabled(true);
					} catch (JSONException e) {
						e.printStackTrace();
					}
					break;
				case JkgcArticlePaser.HELPED:

					break;
				}
			} else {
				if (msg.what == JkgcArticlePaser.FIND) {
					currentState = DEFAULT;
					setDrawable(currentState);
					tv_jkgc_article_collect.setEnabled(true);
				}else {
//					 Toast.makeText(JkgcItemActivity.this,
//							 getString(R.string.common_net_fail), Toast.LENGTH_LONG)
//							 .show();
				}
			}
		}

	};

	String imgUrl; // 图片url
	String contentUrl; // 文章内容url

	/**
	 * 讲从网上获取的数据展示在页面上
	 * 
	 * @param article
	 */
	private void showDataOnView(JkgcArticle article) {

		titleStr = article.getTitle();
		contentStr = article.getBody();
		imgUrl = article.getLitpic();
		contentUrl = article.getUrl();
		tv_curTitle.setText(titleStr);
		new Thread() {
			public void run() {
				runOnUiThread(new Runnable() {
					public void run() {
						webView.getSettings().setLayoutAlgorithm(
								LayoutAlgorithm.SINGLE_COLUMN);
						String[] contentStrArray = contentStr.split("好文推荐:");
						// String tempStr = contentStrArray[0];
						webView.loadDataWithBaseURL(null, contentStrArray[0],
								"text/html", "utf-8", null);
					}
				});

			};
		}.start();
		
		tv_text.setMovementMethod(ScrollingMovementMethod.getInstance());// 滚动

	};


	/* 处理当前页面中的数据； */
	List<String> temps = new ArrayList<String>();

	private String function(String str) {
		String qstr = str.substring(0, str.indexOf("<a href=\"http://www."));// 头部
		String wstr = str.substring(str.indexOf(">") + 1, str.length());// 尾部
		String temp = qstr + wstr;
		if (temp.contains("<")) {
			function(temp);
		}
		temps.add(temp);
		return temps.get(0);

	}


	final Html.ImageGetter imageGetter = new Html.ImageGetter() {

		public Drawable getDrawable(String source) {
			Drawable drawable = null;
			URL url;
			try {
				url = new URL(source);
				drawable = Drawable.createFromStream(url.openStream(), "");
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
			drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
					drawable.getIntrinsicHeight());
			return drawable;
		}
	};

	@Override
	public void preInit() {
		Intent intent = getIntent();
		id = intent.getStringExtra(ID);
		target = intent.getStringExtra(TARGET);
		title = intent.getStringExtra(TITLE);
		userId = getUserId();

	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Stattistics(Sta_Click);
	}
	
	/**
	 * 友盟统计收藏 帮助
	 */
	public void Stattistics(int position){
		Map<String, String> params = new HashMap<String, String>();
		if(contentUrl == null)
			return;
		params.put("url",contentUrl);
		if(position == 0){
			MobclickAgent.onEvent(this, "B00112", params);
		}else if(position ==1){
			MobclickAgent.onEvent(this, "B00113", params);
		}else {
			MobclickAgent.onEvent(this, "Jk_001", params);
		}
	}

	@Override
	public void loadData() {
		// TODO Auto-generated method stub

	}

	@Override
	public void initView() {
		tv_curTitle = (TextView) findViewById(R.id.tv_curTitle);
		tv_text = (TextView) findViewById(R.id.tv_text);
		tv_jkgc_article_good = (ImageView) findViewById(R.id.tv_jkgc_article_good);
		tv_jkgc_article_share = (ImageView) findViewById(R.id.tv_jkgc_article_share);
		tv_jkgc_article_collect = (ImageView) findViewById(R.id.tv_jkgc_article_collect);

		webView = (WebView) findViewById(R.id.webView);

		tv_jkgc_article_good.setOnClickListener(this);
		tv_jkgc_article_share.setOnClickListener(this);
		tv_jkgc_article_collect.setOnClickListener(this);
		helpState = getState(Integer.parseInt(id));
		tv_jkgc_article_collect.setEnabled(false);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_jkgc_article_good:
			// 请求地址
			String actionGood = getString(R.string.find_help);
			// 请求参数
			HashMap<String, Object> inParamsGood = new HashMap<String, Object>();
			inParamsGood.put("type", target); // 所属类别
			inParamsGood.put("userid", userId);
			inParamsGood.put("art_id", id);
			inParamsGood.put("apptype", appid);

			String requestGood = "get";
			switch (helpState) {
			case DEFAULT: // 当前页面状态是默认的；
				helpState = HELPED;
//				tv_jkgc_article_good
//						.setImageResource(R.drawable.btn_detail_tab_1_normal);
				break;
			case HELPED:// 点击帮助的状态
				helpState = DEFAULT;
//				tv_jkgc_article_good
//						.setImageResource(R.drawable.btn_detail_tab_1_pressed);
				saveState(helpState);
				break;
			}
			saveState(helpState);
			Stattistics(Sta_Help);
			break;
		case R.id.tv_jkgc_article_share:
			showShare();
			break;
		case R.id.tv_jkgc_article_collect:
			String actionCollect = null;
			// 请求参数
			HashMap<String, Object> inParamsCollect = new HashMap<String, Object>();
			inParamsCollect.put("type", getType(target)); // 所属类别
			inParamsCollect.put("userid", userId);
			inParamsCollect.put("art_id", id);
			inParamsCollect.put("apptype", appid);

			String requestCollect = "get";
			switch (currentState) {
			case DEFAULT: // 当前页面状态是默认的；
				// 请求地址
				actionCollect = getString(R.string.find_collect);
				state = COLLECTED;
				break;
			case COLLECTED:
				actionCollect = getString(R.string.delete_collect);
				state = DEFAULT;
				break;
			}
			// saveState(state);
			paser.setWhat(JkgcArticlePaser.COLLECT);
			paser.sendMsg(actionCollect, inParamsCollect, requestCollect);
			break;

		default:
			break;
		}

	}

	/**
	 *  
	 */
	private void showShare() {
		ShareSDK.initSDK(this);
		OnekeyShare oks = new OnekeyShare();
		oks.setTitle("云健康");
		oks.setText(titleStr);
		oks.setUrl(contentUrl);
		oks.setImageUrl(imgUrl);
		oks.setDialogMode();
		// 启动分享GUI
		oks.show(this, api);
		
	}

	View.OnClickListener itemsOnClick = new View.OnClickListener() {
		@Override
		public void onClick(View view) {

			switch (view.getId()) {
			case R.id.tv_wjk_plan_share_weixin:
				// Toast.makeText(mContext, "微信", Toast.LENGTH_SHORT).show();
				// window.shareWXPlatform(titleStr, contentStr);
				break;
			case R.id.tv_wjk_plan_share_xlwb:
				// window.shareSina(contentStr);
				break;
			case R.id.tv_wjk_plan_share_qq:
				// window.shareQQPlatform(titleStr, contentStr);
				break;
			case R.id.tv_wjk_plan_share_email:
				break;
			case R.id.tv_wjk_plan_share_pyq:
				// window.shareWXCirclePlatform(titleStr, contentStr);
				break;
			case R.id.tv_wjk_plan_share_txyb:
				// window.shareTencentPlatform(contentStr);
				break;
			}

		}
	};

	private int getType(String target) {
		if (target.equals(NewJkgcActivity.TITLE_KEY[0])) {
			return 1;
		} else if (target.equals(NewJkgcActivity.TITLE_KEY[1])) {
			return 9;
		} else if (target.equals(NewJkgcActivity.TITLE_KEY[2])) {
			return 3;
		} else if (target.equals(NewJkgcActivity.TITLE_KEY[3])) {
			return 4;
		} else if (target.equals(NewJkgcActivity.TITLE_KEY[4])) {
			return 2;
		}
		return 0;
	}

	// 页面状态工具
	private final int DEFAULT = 0; // 当前页面状态是默认的；
	private final int HELPED = 1;// 点击帮助的状态
	private final int COLLECTED = 2;// 点击收藏的状态
	private final int HELPED_AND_COLLECTED = 3;// 帮助和收藏一起的状态
	private final String STATE = "state";
	private int state;

	/**
	 * 保存当前页面状态
	 */
	private void saveState(int state) {

		editor = spState.edit();
		editor.putInt(id + "", state);
		editor.commit();
		setHelpDrawable(state);
	}

	/**
	 * 获取当前页面状态；
	 * 
	 * @return
	 */
	private int getState(int id) {
		spState = getSharedPreferences(STATE, Context.MODE_PRIVATE);
		helpState = spState.getInt(id + "", DEFAULT);
		setHelpDrawable(helpState);
		return helpState;
	}

	/**
	 * 获取用户id。
	 * 
	 * @return
	 */
	private String getUserId() {
		SharedPreferences sp = context.getSharedPreferences("config",
				Context.MODE_PRIVATE);

//		userId = sp.getString("userid", "");
		userId = UserKeeper.getCurrentUser(this).getUserid();
		return userId;
	}

	/**
	 * 设置背景图片
	 * 
	 * @param state
	 */
	private void setDrawable(int state) {
		switch (state) {
		// 点击效果

		case DEFAULT: // 当前页面状态是默认的；
			tv_jkgc_article_collect.setImageResource(R.drawable.btn_detail_tab_3_normal);
			break;
		case COLLECTED:
			tv_jkgc_article_collect.setImageResource(R.drawable.btn_detail_tab_3_pressed);
			break;
		}
	}

	/**
	 * 设置背景图片
	 * 
	 * @param state
	 */
	private void setHelpDrawable(int state) {
		switch (state) {
		// 点击效果

		case DEFAULT: // 当前页面状态是默认的；
//			goodD = this.getResources().getDrawable(
//					R.drawable.btn_detail_tab_1_normal);
			tv_jkgc_article_good.setImageResource(R.drawable.btn_detail_tab_1_normal);
			break;
		case HELPED:// 点击帮助的状态
//			goodD = this.getResources().getDrawable(
//					R.drawable.btn_detail_tab_1_pressed);
			tv_jkgc_article_good.setImageResource(R.drawable.btn_detail_tab_1_pressed);
			break;
		}
//		tv_jkgc_article_good.setImageDrawable(goodD);
	}

	MyProgress progressDialog;

	/**
	 * 打开ProgressDialog表示载入中；
	 */
	private void beganProgressDialog() {
		progressDialog = new MyProgress(JkgcItemActivity.this,15000);
//		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置进度条的形式为圆形转动的进度条
//		progressDialog.setCancelable(true);
//		progressDialog.setCanceledOnTouchOutside(false);
		progressDialog.start();
	}

	private void getState() {
		String actionCollect = null;
		// 请求参数
		HashMap<String, Object> inParamsCollect = new HashMap<String, Object>();
		inParamsCollect.put("userid", userId);
		inParamsCollect.put("apptype", appid);
		String requestCollect = "get";
		if (paser == null)
			paser = new JkgcArticlePaser(this, handler, JkgcArticlePaser.FIND);
		paser.setWhat(JkgcArticlePaser.FIND);
		paser.sendMsg(getString(R.string.me_collect_list), inParamsCollect,
				requestCollect);
	}

	/**
	 * 关闭ProgressDialog载入成功或者失败；
	 */
	private void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.stop();
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		stopProgressDialog();
	}
}
